<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>用户登录</title>

    <style>
        h1{color: red;}
        input{padding: 10px;margin: 6px;border-radius: 6px;}
        .msg{color: red;margin: 20px 0;}
    </style>

</head>
<body>
<?php
$xh=$_COOKIE['xh'];
$pwd=$_COOKIE['pwd'];
$remember=$_COOKIE['remember'];
if ($_POST){
    try {
        if ($_POST['remember']){
            setcookie('xh',$_POST['xh'],time() + 7 * 24 * 3600);
            setcookie('pwd',$_POST['pwd'],time() + 7 * 24 * 3600);
            setcookie('remember',$_POST['remember'],time() + 7 * 24 * 3600);
        }else{
            setcookie('xh');
            setcookie('pwd');
            setcookie('remember');
        }
        $db=new PDO("mysql:host=localhost; dbname=db", 'root', 'root');
        $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
        $ps=$db->prepare('select * from students where xh=? and pwd=?');
        $rs=$ps->execute([$_POST['xh'],$_POST['pwd']]);
        $r=$ps->fetch();
        session_start();
        if ($r===false){
            unset($_SESSION['user']);
            throw new Exception('你输入的用户名或密码错误');
        } else{
            $_SESSION['user']=$r;
            header(header:'Location:index.php');
            return;
        }
    }catch (PDOException $e){
        $msg=$e->getMessage();
    }
}
?>
<h1>用户登录</h1>
<form method="post">
    学号:<input type="text" name="xh" value="<?=$_POST['xh']??$xh?>"><br>
    密码:<input type="password" name="pwd" value="<?=$_POST['pwd']??$pwd?>"><br>
    <input type="checkbox" name="remember" <?=$_POST?($_POST['remember']?'checked':''):($remember=='on'?'checked':'')?>/>记住密码<br>
    <div class="msg"><?=$msg?></div>
    <input type="submit" value="登录">
    <input type="button" value="注册新用户" onclick="location.href='modify.php'">
</form>

</body>
</html>
